﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.GameContent.UI.Elements;
using Terraria.Graphics;
using Terraria.Localization;
using Terraria.ModLoader.IO;
using Terraria.UI;

namespace Terraria.ModLoader.UI
{
	// Token: 0x020002B0 RID: 688
	internal class UIModSourceItem : UIPanel
	{
		// Token: 0x06001B42 RID: 6978 RVA: 0x0042FDE8 File Offset: 0x0042DFE8
		public UIModSourceItem(string mod, LocalMod builtMod)
		{
			this.mod = mod;
			this.BorderColor = new Color(89, 116, 213) * 0.7f;
			this.dividerTexture = TextureManager.Load("Images/UI/Divider");
			this.Height.Set(90f, 0f);
			this.Width.Set(0f, 1f);
			base.SetPadding(6f);
			string str = Path.GetFileName(mod).Contains(" ") ? string.Format("  [c/FF0000:{0}]", Language.GetTextValue("tModLoader.MSModSourcesCantHaveSpaces")) : "";
			this.modName = new UIText(Path.GetFileName(mod) + str, 1f, false);
			this.modName.Left.Set(10f, 0f);
			this.modName.Top.Set(5f, 0f);
			base.Append(this.modName);
			UITextPanel<string> uitextPanel = new UITextPanel<string>(Language.GetTextValue("tModLoader.MSBuild"), 1f, false);
			uitextPanel.Width.Set(100f, 0f);
			uitextPanel.Height.Set(30f, 0f);
			uitextPanel.Left.Set(10f, 0f);
			uitextPanel.Top.Set(40f, 0f);
			uitextPanel.PaddingTop -= 2f;
			uitextPanel.PaddingBottom -= 2f;
			uitextPanel.OnMouseOver += UICommon.FadedMouseOver;
			uitextPanel.OnMouseOut += UICommon.FadedMouseOut;
			uitextPanel.OnClick += this.BuildMod;
			base.Append(uitextPanel);
			UITextPanel<string> uitextPanel2 = new UITextPanel<string>(Language.GetTextValue("tModLoader.MSBuildReload"), 1f, false);
			uitextPanel2.CopyStyle(uitextPanel);
			uitextPanel2.Width.Set(200f, 0f);
			uitextPanel2.Left.Set(150f, 0f);
			uitextPanel2.OnMouseOver += UICommon.FadedMouseOver;
			uitextPanel2.OnMouseOut += UICommon.FadedMouseOut;
			uitextPanel2.OnClick += this.BuildAndReload;
			base.Append(uitextPanel2);
			this.builtMod = builtMod;
			if (builtMod != null)
			{
				UITextPanel<string> uitextPanel3 = new UITextPanel<string>(Language.GetTextValue("tModLoader.MSPublish"), 1f, false);
				uitextPanel3.CopyStyle(uitextPanel2);
				uitextPanel3.Width.Set(100f, 0f);
				uitextPanel3.Left.Set(390f, 0f);
				uitextPanel3.OnMouseOver += UICommon.FadedMouseOver;
				uitextPanel3.OnMouseOut += UICommon.FadedMouseOut;
				uitextPanel3.OnClick += this.Publish;
				base.Append(uitextPanel3);
			}
			base.OnDoubleClick += this.BuildAndReload;
		}

		// Token: 0x06001B43 RID: 6979 RVA: 0x004300E4 File Offset: 0x0042E2E4
		protected override void DrawSelf(SpriteBatch spriteBatch)
		{
			base.DrawSelf(spriteBatch);
			CalculatedStyle innerDimensions = base.GetInnerDimensions();
			Vector2 position = new Vector2(innerDimensions.X + 5f, innerDimensions.Y + 30f);
			spriteBatch.Draw(this.dividerTexture, position, null, Color.White, 0f, Vector2.Zero, new Vector2((innerDimensions.Width - 10f) / 8f, 1f), SpriteEffects.None, 0f);
		}

		// Token: 0x06001B44 RID: 6980 RVA: 0x000132A0 File Offset: 0x000114A0
		public override void MouseOver(UIMouseEvent evt)
		{
			base.MouseOver(evt);
			this.BackgroundColor = new Color(73, 94, 171);
			this.BorderColor = new Color(89, 116, 213);
		}

		// Token: 0x06001B45 RID: 6981 RVA: 0x0042C064 File Offset: 0x0042A264
		public override void MouseOut(UIMouseEvent evt)
		{
			base.MouseOut(evt);
			this.BackgroundColor = new Color(63, 82, 151) * 0.7f;
			this.BorderColor = new Color(89, 116, 213) * 0.7f;
		}

		// Token: 0x06001B46 RID: 6982 RVA: 0x00430168 File Offset: 0x0042E368
		public override int CompareTo(object obj)
		{
			UIModSourceItem uimodSourceItem = obj as UIModSourceItem;
			if (uimodSourceItem == null)
			{
				return base.CompareTo(obj);
			}
			if (uimodSourceItem.builtMod == null && this.builtMod == null)
			{
				return this.modName.Text.CompareTo(uimodSourceItem.modName.Text);
			}
			if (uimodSourceItem.builtMod == null)
			{
				return -1;
			}
			if (this.builtMod == null)
			{
				return 1;
			}
			return uimodSourceItem.builtMod.lastModified.CompareTo(this.builtMod.lastModified);
		}

		// Token: 0x06001B47 RID: 6983 RVA: 0x000138E2 File Offset: 0x00011AE2
		private void BuildMod(UIMouseEvent evt, UIElement listeningElement)
		{
			Main.PlaySound(10, -1, -1, 1, 1f, 0f);
			ModLoader.modToBuild = this.mod;
			ModLoader.reloadAfterBuild = false;
			ModLoader.buildAll = false;
			Main.menuMode = 10003;
		}

		// Token: 0x06001B48 RID: 6984 RVA: 0x0001391A File Offset: 0x00011B1A
		private void BuildAndReload(UIMouseEvent evt, UIElement listeningElement)
		{
			Main.PlaySound(10, -1, -1, 1, 1f, 0f);
			ModLoader.modToBuild = this.mod;
			ModLoader.reloadAfterBuild = true;
			ModLoader.buildAll = false;
			Main.menuMode = 10003;
		}

		// Token: 0x06001B49 RID: 6985 RVA: 0x004301E4 File Offset: 0x0042E3E4
		private void Publish(UIMouseEvent evt, UIElement listeningElement)
		{
			if (ModLoader.modBrowserPassphrase == "")
			{
				Main.menuMode = 10015;
				Interface.enterPassphraseMenu.SetGotoMenu(10001);
				return;
			}
			Main.PlaySound(10, -1, -1, 1, 1f, 0f);
			try
			{
				TmodFile modFile = this.builtMod.modFile;
				BuildProperties properties = this.builtMod.properties;
				List<UploadFile> list = new List<UploadFile>();
				list.Add(new UploadFile
				{
					Name = "file",
					Filename = Path.GetFileName(modFile.path),
					Content = File.ReadAllBytes(modFile.path)
				});
				if (modFile.HasFile("icon.png"))
				{
					list.Add(new UploadFile
					{
						Name = "iconfile",
						Filename = "icon.png",
						Content = modFile.GetFile("icon.png")
					});
				}
				if (properties.beta)
				{
					throw new WebException(Language.GetTextValue("tModLoader.BetaModCantPublishError"));
				}
				NameValueCollection nameValueCollection = new NameValueCollection();
				nameValueCollection.Add("displayname", properties.displayName);
				nameValueCollection.Add("name", modFile.name);
				nameValueCollection.Add("version", "v" + properties.version);
				nameValueCollection.Add("author", properties.author);
				nameValueCollection.Add("homepage", properties.homepage);
				nameValueCollection.Add("description", properties.description);
				nameValueCollection.Add("steamid64", ModLoader.SteamID64);
				nameValueCollection.Add("modloaderversion", "tModLoader v" + modFile.tModLoaderVersion);
				nameValueCollection.Add("passphrase", ModLoader.modBrowserPassphrase);
				nameValueCollection.Add("modreferences", string.Join(", ", from x in properties.modReferences
				select x.mod));
				nameValueCollection.Add("modside", properties.side.ToFriendlyString());
				NameValueCollection values = nameValueCollection;
				ServicePointManager.Expect100Continue = false;
				string uriString = "http://javid.ddns.net/tModLoader/publishmod.php";
				using (UIModSourceItem.PatientWebClient client = new UIModSourceItem.PatientWebClient())
				{
					ServicePointManager.ServerCertificateValidationCallback = ((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) => true);
					Interface.uploadMod.SetDownloading(modFile.name);
					Interface.uploadMod.SetCancel(delegate
					{
						Main.menuMode = 10001;
						client.CancelAsync();
					});
					client.UploadProgressChanged += delegate(object s, UploadProgressChangedEventArgs e)
					{
						Interface.uploadMod.SetProgress(e);
					};
					client.UploadDataCompleted += delegate(object s, UploadDataCompletedEventArgs e)
					{
						this.PublishUploadDataComplete(s, e, modFile);
					};
					string str = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
					client.Headers["Content-Type"] = "multipart/form-data; boundary=" + str;
					byte[] uploadFilesRequestData = UploadFile.GetUploadFilesRequestData(list, values);
					client.UploadDataAsync(new Uri(uriString), uploadFilesRequestData);
				}
				Main.menuMode = 10021;
			}
			catch (WebException e)
			{
				WebException e2;
				ErrorLogger.LogModBrowserException(e2);
			}
		}

		// Token: 0x06001B4A RID: 6986 RVA: 0x00430598 File Offset: 0x0042E798
		private void PublishUploadDataComplete(object s, UploadDataCompletedEventArgs e, TmodFile theTModFile)
		{
			if (e.Error == null)
			{
				byte[] result = e.Result;
				int num = result.Length;
				if (result.Length > 256 && result[result.Length - 256 - 1] == 126)
				{
					using (FileStream fileStream = File.Open(theTModFile.path, FileMode.Open, FileAccess.ReadWrite))
					{
						using (BinaryReader binaryReader = new BinaryReader(fileStream))
						{
							using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
							{
								binaryReader.ReadBytes(4);
								binaryReader.ReadString();
								binaryReader.ReadBytes(20);
								if (fileStream.Length - fileStream.Position > 256L)
								{
									binaryWriter.Write(result, result.Length - 256, 256);
								}
							}
						}
					}
					num -= 257;
				}
				string @string = Encoding.UTF8.GetString(result, 0, num);
				ErrorLogger.LogModPublish(@string);
				return;
			}
			if (e.Cancelled)
			{
				Main.menuMode = 10001;
				return;
			}
			ErrorLogger.LogModBrowserException(e.Error);
		}

		// Token: 0x04001872 RID: 6258
		private string mod;

		// Token: 0x04001873 RID: 6259
		private Texture2D dividerTexture;

		// Token: 0x04001874 RID: 6260
		private UIText modName;

		// Token: 0x04001875 RID: 6261
		private LocalMod builtMod;

		// Token: 0x020002B1 RID: 689
		private class PatientWebClient : WebClient
		{
			// Token: 0x06001B4B RID: 6987 RVA: 0x004306C4 File Offset: 0x0042E8C4
			protected override WebRequest GetWebRequest(Uri uri)
			{
				HttpWebRequest httpWebRequest = (HttpWebRequest)base.GetWebRequest(uri);
				httpWebRequest.Timeout = -1;
				httpWebRequest.AllowWriteStreamBuffering = false;
				return httpWebRequest;
			}
		}
	}
}
